<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        outline: 1px solid red;
      }
    </style>
  </head>
  <body>
    <canvas width="300" height="300" id="canvas"></canvas>
    <script>
      let canvas = document.querySelector("#canvas");
      let context = canvas.getContext("2d");

      class Dot {
        constructor({
          x,
          y,
          speedX = 1,
          speedY = 0.1,
          color = "#" + Math.random().toString(16).slice(-6),
        }) {
          this.x = x;
          this.y = y;
          this.speedX = speedX;
          this.speedY = speedY;
          this.color = color;
        }

        // 实例方法
        update() {
          // 原型对象的方法里面的this指向的是 实例对象
          //   console.log(this);
          this.x += this.speedX;
          this.y += this.speedY;
          //   return this;

          if (this.x >= 290 || this.x <= 10) {
            this.speedX = -this.speedX;
          }
          if (this.y >= 290 || this.y <= 10) {
            this.speedY = -this.speedY;
          }
        }

        draw() {
          context.beginPath();
          context.arc(this.x, this.y, 10, 0, 2 * Math.PI);
          context.fillStyle = this.color;
          context.fill();
        }
      }

      //   var x1 = new Dot({
      //     x: 150,
      //     y: 150,
      //     speedX: -1,
      //     speedY: 0.1,
      //     color: "red",
      //   });
      //   var x2 = new Dot({ x: 100, y: 100 });

      //   初始点
      let dots = [
        new Dot({
          x: 150,
          y: 150,
          speedX: -1,
          speedY: 0.1,
          color: "red",
        }),
        new Dot({ x: 100, y: 100 }),
      ];

      setInterval(() => {
        //   清空画布
        context.clearRect(0, 0, 300, 300);

        dots.forEach((dot) => {
          dot.update();
          dot.draw();
        });
      }, 1000 / 60);
    </script>
  </body>
</html>
